﻿using System;
using NRCP.BusinessLogicLayer;
using NRCP.Helpers;
using NRCP.BusinessEntities;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;

namespace NRCP
{
    public partial class Plan_Details : System.Web.UI.Page
    {
        List<NationalPlanDetailsYearly> yearlyPlan = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            NationalPlanBLL planbll = new NationalPlanBLL();
            litPlanYear.Text = planbll.GetNationalPlanById(SiteUtility.IntQueryParam).PlanYear.ToString();

            NationalPlanDetailsYearlyBLL bll = new NationalPlanDetailsYearlyBLL();
            yearlyPlan=bll.GetNationalPlanDetailsYearliesByNationalPlanId(SiteUtility.IntQueryParam);
            var orderGroups = from p in yearlyPlan
                              group p by p.NationalPlanFish.Fish.Name into g
                              select new { Category = g.Key, TotalUnits = g.Sum(p => p.Count) };
            List<TempValueObject> fishes = orderGroups.ToList().ConvertAll(x => new TempValueObject { Key = x.Category, Value = x.TotalUnits.ToString() });
            litGrandTotal.Text = yearlyPlan.Sum(w => w.Count).ToString();
            repTotalBreakdown.DataSource = fishes;
            repTotalBreakdown.DataBind();           

            NationalPlanFishBLL fishbll = new NationalPlanFishBLL();
            repFishes.DataSource = fishbll.GetNationalPlanFishByNationalPlanId(SiteUtility.IntQueryParam);
            repFishes.DataBind();           
        }

        protected void repFishes_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
            {
                NationalPlanFish fish = e.Item.DataItem as NationalPlanFish;
                if (fish != null)
                {
                    Repeater repBreakdownByGroups = e.Item.FindControl("repBreakdownByGroups") as Repeater;
                    if (repBreakdownByGroups != null)
                    {
                        List<NationalPlanDetailsYearly> tmp = yearlyPlan.Where(obj => obj.FishId == fish.Id).ToList();
                        repBreakdownByGroups.DataSource = tmp; 
                        repBreakdownByGroups.DataBind();
                    }
                }
            }
        }


    }
}